package com.wf.netty.coder.string;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.embedded.EmbeddedChannel;
import org.junit.jupiter.api.Test;

import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;

/**
 * 功能描述
 *
 * @author wf
 * @since 2022/5/26
 */
public class StringDecoderTest {
    private static String content = "test123!!!";

    @Test
    public void testSubpackage() {
        ChannelInitializer<EmbeddedChannel> channelInitializer = new ChannelInitializer<EmbeddedChannel>() {
            @Override
            protected void initChannel(EmbeddedChannel ch) throws Exception {
                ch.pipeline().addLast(new StringReplayDecoder());
                ch.pipeline().addLast(new StringProcessHandler());
            }
        };
        EmbeddedChannel embeddedChannel = new EmbeddedChannel(channelInitializer);
        byte[] bytes = content.getBytes(StandardCharsets.UTF_8);
        SecureRandom secureRandom = new SecureRandom();
        for (int i = 0; i < 10; i++) {
            int random = secureRandom.nextInt(3) + 1;
            ByteBuf buf = Unpooled.buffer();
            //发送长度：字节数组长度*重复次数
            buf.writeInt(bytes.length * random);
//            embeddedChannel.writeInbound(buf);

            //重复拷贝content的字节数据到发送缓冲区
            for (int k = 0; k < random; k++) {
                buf.writeBytes(bytes);
            }
            //发送内容：发送buf缓冲区
            embeddedChannel.writeInbound(buf);
        }

    }
}
